import env from "../config/env";
import { escape } from "querystring";
const { accessKey, secretKey } = env.qiniu;


class QiniuService {
    public qiniu: any;
    public client: any;
    constructor(private accessKey, private secretKey) {
        this.qiniu = require('qiniu');
        this.qiniu.conf.ACCESS_KEY = this.accessKey;
        this.qiniu.conf.SECRET_KEY = this.secretKey;
        this.client = new this.qiniu.rs.Client();
    }

    public uptoken() {
        let bucketName = env.qiniu.bucket;
        let putPolicy = new this.qiniu.rs.PutPolicy(bucketName);
        let token = putPolicy.token();
        return { token };
    }

    public uploadFile({ uptoken, key, localFile }) {
        let extra = new this.qiniu.io.PutExtra();
        this.qiniu.io.putFile(uptoken, key, localFile, extra, function (err, ret) {
            if (!err) {
                console.log(ret.hash, ret.key, ret.persistentId);
            } else {
                console.log(err);
            }
        })
    }

    public deleteFile({ bucket, key }) {
        this.client.remove(bucket, key, function (err, ret) {
            if (!err) {
                console.log(ret);
            } else {
                console.log(err);
            }
        })
    }
}

const qiniuService = new QiniuService(accessKey, secretKey)

export { qiniuService };
